// K&R book. C7, p143.
// cat function. V2.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fp;
    FILE *fp2;
    void filecopy(FILE *, FILE *);
    char *prog = argv[0];

    if ((fp2 = fopen("c.txt", "w")) == NULL)
        fprintf(stderr, "Can't open c.txt\n");

    if (argc == 1)
        filecopy(stdin, stdout);
    else
        while (--argc > 0)
        {
            if ((fp = fopen(*++argv, "r")) == NULL)
            {
                fprintf(stderr, "Program %s can't open file: %s\n", prog, *argv);
                exit(1);
            }
            else
            {
                filecopy(fp, fp2);
                fclose(fp);
            }
        }
    if (ferror(stdout))
    {
        fprintf(stderr, "%s: error with writing stdout.\n", prog);
        exit(2);
    }
    exit(0);
}

void filecopy(FILE *infile, FILE *outfile)
{
    char c;

    while ((c = getc(infile)) != EOF)
        putc(c, outfile);
}